package com.skyline.common.tag;

import java.io.IOException;

import javax.servlet.jsp.JspException;
import javax.servlet.jsp.tagext.TagSupport;

import org.apache.commons.lang.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

//TODO：加注释
public class AjaxPageTag extends TagSupport {
	private static final Log LOGGER = LogFactory.getLog(AjaxPageTag.class);
	private static final long serialVersionUID = 1787065628804803098L;

	private String objId;
	private String curClass;
	private String curStyle;
	private String normalClass;
	private String normalStyle;
	private String decStr;
	private String firstFunc;
	private String successFunc;
	private String errorFunc;
	private String beforeSendFunc;
	private String completeFunc;
	private Integer maxSize;
	private String url;
	private String paramStr;
	private boolean hasParam;
	private Boolean arcCur;
	private String pageKey;
	private String pageDivId;
	private static final String JUMP_FUNCTION_NAME = "jumpTo";
	private static final String AJAX_BACK_FUNCTION_NAME = "ajaxPageBack";

	@Override
	public int doEndTag() throws JspException {
		try {
			pageContext.getOut().println(generateTotleScript());
		} catch (IOException e) {
			LOGGER.warn("生成ajaxPage出错", e);
		}
		setToDefault();
		return EVAL_BODY_INCLUDE;
	}

	private void setToDefault() {
		objId = null;
		curClass = null;
		curStyle = null;
		normalClass = null;
		normalStyle = null;
		decStr = null;
		firstFunc = null;
		successFunc = null;
		errorFunc = null;
		beforeSendFunc = null;
		completeFunc = null;
		maxSize = 5;
		url = null;
		paramStr = null;
		hasParam = false;
		arcCur = false;
		pageKey = null;
		pageDivId = null;
	}

	private String generateTotleScript() {
		StringBuilder buffer = new StringBuilder("<script type=\"text/javascript\">");
		buffer.append("var ");
		buffer.append(objId);
		buffer.append("={\n");
		buffer.append(generatePageSetting());
		buffer.append(",\n");
		buffer.append(generateAjaxBack());
		buffer.append(",\n");
		buffer.append(generateFirstAskFunc());
		buffer.append(",\n");
		buffer.append(generateJumpTo());
		buffer.append("}\n</script>");
		return buffer.toString();
	}

	/**
	 * 产生Ajax请求
	 * 
	 * <pre>
	 * doAjax(url,paramStr+'curpage='+curpage,backFunc,errorFunc,beforeSendFunc);
	 * </pre>
	 */
	private String generateAjaxAsk(String curpage) {
		StringBuilder buffer = new StringBuilder("doAjax('");
		buffer.append(url);
		buffer.append("','");
		if (paramStr == null) {
			buffer.append("curpage='+");
			buffer.append(curpage);
		} else {
			if (hasParam) {
				buffer.append(paramStr);
				buffer.append("&curpage='+");
				buffer.append(curpage);
			} else {
				buffer.append("curpage='+");
				buffer.append(curpage);
			}
		}
		buffer.append(',');
		buffer.append(objId);
		buffer.append('.');
		buffer.append(AJAX_BACK_FUNCTION_NAME);
		if (errorFunc != null) {
			buffer.append(',');
			buffer.append(errorFunc);
		}
		if (beforeSendFunc != null) {
			buffer.append(',');
			buffer.append(beforeSendFunc);
		}
		if (completeFunc != null) {
			buffer.append(',');
			buffer.append(completeFunc);
		}
		buffer.append(");");
		return buffer.toString();
	}

	/**
	 * 产生Ajax回调
	 * 
	 * <pre>
	 * ajaxPageBack:function(data){
	 * var page=data.pageKey;
	 * jQuery('#pageDiv').html(pagination.generateTotalStr(page));
	 * successFunc(data);
	 * }
	 * </pre>
	 */
	private String generateAjaxBack() {
		StringBuilder buffer = new StringBuilder(AJAX_BACK_FUNCTION_NAME);
		buffer.append(":function(data){\n");
		buffer.append("var page=data.");
		buffer.append(pageKey);
		buffer.append(";\n");
		String[] divIds = pageDivId.split(",");
		buffer.append(genDivUrlFunc(divIds));
		buffer.append(successFunc);
		buffer.append("(data);\n}\n");
		return buffer.toString();
	}

	private String genDivUrlFunc(String[] divIds) {
		StringBuilder buffer = new StringBuilder();
		for (String divId : divIds) {
			buffer.append("jQuery('#");
			buffer.append(divId);
			buffer.append("').html(");
			buffer.append(objId);
			buffer.append(".pagination.generateTotalStr(page));\n");
		}
		return buffer.toString();
	}

	/**
	 * 产生第一次请求函数
	 * 
	 * <pre>
	 * firstFunc:function(){
	 * return doAjax(url,paramStr+'curpage='+1,backFunc,errorFunc);
	 * }
	 * </pre>
	 */
	private String generateFirstAskFunc() {
		String funcName = firstFunc;
		StringBuilder buffer = new StringBuilder(funcName);
		buffer.append(":function(){\n").append("return ");
		buffer.append(generateAjaxAsk("1"));
		buffer.append("\n}\n");
		return buffer.toString();
	}

	/**
	 * 产生跳转函数
	 * 
	 * <pre>
	 * jumpTo:function (i){
	 * return doAjax(url,paramStr+'curpage='+i,backFunc,errorFunc);
	 * }
	 * </pre>
	 */
	private String generateJumpTo() {
		StringBuilder buffer = new StringBuilder(JUMP_FUNCTION_NAME);
		buffer.append(":function").append("(i){\n");
		buffer.append(generateAjaxAsk("i"));
		buffer.append("\n}\n");
		return buffer.toString();
	}

	/**
	 * 产生分页设置
	 * 
	 * <pre>
	 * pagination:new Pagination({
	 * arcCur:arcCur,
	 * curClassStr:&quot;curClass&quot;,
	 * curStyleStr:&quot;curStyle&quot;,
	 * norClassStr:&quot;normalClass&quot;,
	 * norStyleStr:&quot;normalStyle&quot;,
	 * decStr:&quot;decStr&quot;,
	 * pageObj:&quot;objId&amp;quot,
	 * maxSize:maxSize
	 * })
	 * </pre>
	 */
	private String generatePageSetting() {
		StringBuilder buffer = new StringBuilder("pagination:new  Pagination({arcCur:");
		boolean arc = arcCur == null ? false : arcCur;
		buffer.append(arc);
		buffer.append(",curClassStr:\"");
		buffer.append(StringUtils.trimToEmpty(curClass));
		buffer.append("\",curStyleStr:\"");
		buffer.append(StringUtils.trimToEmpty(curStyle));
		buffer.append("\",norClassStr:\"");
		buffer.append(StringUtils.trimToEmpty(normalClass));
		buffer.append("\",norStyleStr:\"");
		buffer.append(StringUtils.trimToEmpty(normalStyle));
		buffer.append("\",decStr:\"");
		buffer.append(StringUtils.trimToEmpty(decStr));
		buffer.append("\",pageObj:\"");
		buffer.append(objId);
		buffer.append("\",maxSize:");
		buffer.append(maxSize);
		buffer.append("})");
		return buffer.toString();
	}

	public void setObjId(String objId) {
		objId = StringUtils.trimToNull(objId);
		this.objId = (objId == null) ? "p" : objId;
	}

	public void setCurClass(String curClass) {
		this.curClass = curClass;
	}

	public void setCurStyle(String curStyle) {
		this.curStyle = curStyle;
	}

	public void setNormalClass(String normalClass) {
		this.normalClass = normalClass;
	}

	public void setNormalStyle(String normalStyle) {
		this.normalStyle = normalStyle;
	}

	public void setDecStr(String decStr) {
		this.decStr = decStr;
	}

	public void setFirstFunc(String firstFunc) {
		this.firstFunc = firstFunc;
	}

	public void setSuccessFunc(String successFunc) {
		this.successFunc = successFunc;
	}

	public void setErrorFunc(String errorFunc) {
		this.errorFunc = errorFunc;
	}

	public void setBeforeSendFunc(String beforeSendFunc) {
		this.beforeSendFunc = beforeSendFunc;
	}

	public void setCompleteFunc(String completeFunc) {
		this.completeFunc = completeFunc;
	}

	public void setMaxSize(Integer maxSize) {
		this.maxSize = maxSize;
	}

	public void setUrl(String url) {
		this.url = url;
	}

	public void setParamStr(String paramStr) {
		this.paramStr = StringUtils.trimToNull(paramStr);
		if (null == this.paramStr) {
			hasParam = false;
		} else {
			hasParam = true;
		}
	}

	public void setArcCur(Boolean arcCur) {
		this.arcCur = arcCur;
	}

	public void setPageKey(String pageKey) {
		this.pageKey = pageKey;
	}

	public void setPageDivId(String pageDivId) {
		this.pageDivId = pageDivId;
	}

	public static void main(String... strings) {
		AjaxPageTag tag = new AjaxPageTag();
		tag.setObjId("objId");
		// tag.setCurClass("curClass");
		// tag.setCurStyle("curStyle");
		// tag.setNormalClass("normalClass");
		// tag.setNormalStyle("normalStyle");
		// tag.setDecStr(" decStr");
		tag.setFirstFunc("firstFunc");
		tag.setSuccessFunc("successFunc");
		tag.setErrorFunc("errorFunc");
		tag.setMaxSize(5);
		tag.setUrl("url");
		// tag.setParamStr("paramStr");
		// tag.setArcCur(false);
		tag.setPageKey("pageKey");
		tag.setPageDivId("pageDivId");
		System.out.println(tag.generateTotleScript());
	}

}
